<?php 
namespace app\index\controller;

use app\common\model\Article as ArticleModel;
use app\common\model\Badge;
use app\common\controller\Richtext;
use app\common\model\Bloger;
use think\db\Query;
use app\common\model\ArticleEval;
use app\common\controller\Gravatar;

class Articles extends Base
{
	/**
	 * 获取文章排行
	 * @return unknown
	 */
	public function getSort()
	{
		$sort =   ArticleModel::where([['state','>',0]])->order('see_num desc')->limit(5)->select()->toArray();
		foreach ($sort as &$row) {
			$row['content'] = Richtext::getStirng($row['content'],30).'...';
		}
		return $sort;
	}
	/**
	 * 获取标签库
	 * @return unknown
	 */
	public function getBadges()
	{
		$badges = Badge::where(['state' => 1])->select()->toArray();
		return $badges;
	}
	
	/**
	 * 获取文章列表
	 * @return unknown
	 */
	public function getArticle($is_page = '',$condition=[])
	{
		if (count($condition)) {
			$where = $condition;
			$where[] = ['state','>',0];
		} else {
			$where[] = ['state','>',0];
		}
		if ($is_page) {
			$article = ArticleModel::where($where)->order('state desc,id desc')->paginate(5)->toArray();
			foreach ($article['data'] as &$rows) {
				$rows['content'] = Richtext::getStirng($rows['content'],100).'...';
				$rows['badge_name'] = Badge::get($rows['badge'])->name;
			}
		} else {
			$article = ArticleModel::where($where)->order('state desc,id desc')->limit(10)->select()->toArray();
			foreach ($article as &$rows) {
				$rows['content'] = Richtext::getStirng($rows['content'],100).'...';
				$rows['badge_name'] = Badge::get($rows['badge'])->name;
			}
		}
		return $article;
	}
	
	/**
	 * 获取博主信息
	 * @return unknown
	 */
	public function getBloger()
	{
		return Bloger::get(1)->toArray();
	}
	
	/**
	 * 系统推荐文章
	 * @return array
	 */
	public function getComments()
	{
		$sort = db()->query($sql = "SELECT * FROM `db_article` ORDER BY RAND() LIMIT 5");
		foreach ($sort as &$row) {
			$row['content'] = Richtext::getStirng($row['content'],30).'...';
		}
		return $sort;
	}
	
	/**
	 * 获取文章评论
	 * @param int $article_id 文章编号ID
	 * @return array
	 */
	public function getArticleEval($article_id)
	{
		//获取以及评论
		$list = ArticleEval::where(['article_id' => $article_id,'reply_id' => 0])->order('id desc')->paginate(5)->toArray();
		foreach ($list['data'] as &$rows) {
			$child = ArticleEval::where(['article_id' => $article_id,'reply_level' => $rows['id']])->order('id desc')->select()->toArray();
			foreach ($child as &$row) {
				$row['is_reply'] = false;
				$row['reply_btn'] = '回复';
				$row['sender_headimg'] = Gravatar::getGravatar($row['sender_email']);
			}
			$rows['child'] = $child;
			$rows['is_reply'] = false;
			$rows['reply_btn'] = '回复';
			$rows['sender_headimg'] = Gravatar::getGravatar($rows['sender_email']);
		}
		return $list['data'];
	}
}